from django.contrib.auth import logout
from django.http import HttpResponse
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, filters
from rest_framework.authtoken import views
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from .filters import *
from .serializers import *
from guardian.shortcuts import assign_perm

class UserRegViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    """用户注册"""

    def get_queryset(self):
        queryset = User.objects.all()
        name = self.request.query_params.get('name')
        if name:
            queryset = queryset.filter(username__icontains=name)
        return queryset

    serializer_class = UserRegSerializer



class OptionsTypeViewSet(viewsets.ModelViewSet):
    """选项管理"""
    filter_backends = (DjangoFilterBackend,)
    filter_class = OptionFilter
    queryset = Option.objects.all()
    serializer_class = OptionsTypeSerializer


# RestFrameWork自带的token返回视图中不包含code字段，故此处重写post方法加上code字段
class MyObtainAuthToken(views.ObtainAuthToken):
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({'status': 200, 'data':   {'token': token.key}})


# 转换成类视图
obtain_auth_token = MyObtainAuthToken.as_view()


class Userinfo(views.ObtainAuthToken):
    def get(self, request, *args, **kwargs):
        return Response({'roles':['admin'], 'name':'fyb', 'avatar':233, 'introduction':'233'})


obtain_auth_token2 = Userinfo.as_view()


class Userlogout(views.ObtainAuthToken):
    def get(self, request, *args, **kwargs):
        return Response({'status': 200, 'data': 'success' })

obtain_auth_token3 = Userlogout.as_view()


# def test(request):
#     objects = ProductSource.objects.all()
#     for i in objects:
#         i.classify()
#     return HttpResponse('ok')

def test(request):
    objects = Customer.objects.all()
    for i in objects:
        assign_perm('view_customer',i.F001,i)
        assign_perm('change_customer',i.F001,i)
        assign_perm('delete_customer',i.F001,i)
        assign_perm('add_customer',i.F001,i)
    return HttpResponse('ok')